package com.easy.interceptor;

import com.alibaba.fastjson.JSON;
import com.easy.common.CommonResult;
import com.easy.utils.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //在处理handler之前执行
        //返回true  可以执行对应的handler 返回false 执行不到handler
        //return true/false是springmvc中的运行路线需求   不是回应给浏览器的

        //验证每个请求是否是登陆状态

        //判断登录状态   有token  token有效

        //token在header的Authorization中
        String token = request.getHeader("Authorization");
        if(token != null && JWTUtil.verifyToken(token)){
            //有token  token有效   有登录状态
            return true;
        }else {
            //要回应的数据
            CommonResult result = CommonResult.fail(400,"请登录后再访问");
            //将数据解析成JSON
            String json = JSON.toJSONString(result);
            //将数据回应回去
            response.getWriter().write(json);
            return false;
        }
    }
}
